<?php

namespace App\Services\Assess;

use App\Helpers\JwtUtils;
use App\Models\Account\UserAccountModel;
use App\Models\Account\UserEmailModel;
use App\Models\Assess\ActivateUserManagementEmailModel;
use App\Models\Assess\ActivateUserManagementTagModel;
use App\Models\Assess\AutoEmailModel;
use App\Models\Assess\AutoEmailSkuModel;
use App\Models\Assess\CommentGuideLinkModel;
use App\Models\Assess\CommentGuideLinkUserModel;
use App\Models\Assess\EmailTemplateModel;
use App\Models\Assess\EvaluationMonitorConnectModel;
use App\Models\Assess\EvaluationMonitoringModel;
use App\Models\Assess\GiftModel;
use App\Models\Assess\GiftPlatformSkuModel;
use App\Models\Assess\OrderAndCustomersOrderDetailModel;
use App\Models\Assess\OrderAndCustomersOrderExtendModel;
use App\Models\Assess\OrderAndCustomersOrderModel;
use App\Models\Assess\SendLogModel;
use App\Models\Assess\TagManageModel;
use App\Models\Assess\VisitorsRecordModel;
use App\Models\Register\ActivateUserManagementInfoModel;
use App\Models\Register\ActivateUserManagementModel;
use App\Models\UserModel;
use App\Services\BaseService;
use App\Services\Common\CommonService;
use App\Services\Common\RedisService;
use Illuminate\Support\Facades\Log;
use PHPMailer\PHPMailer\PHPMailer;
use Symfony\Component\Config\Definition\Exception\Exception;

class ActivateService extends BaseService
{
    //搜索条件
    public $searchField = [
        'order_id' => '订单号',
        'email' => '邮箱',
        'platform_sku' => 'Sku',
        'asin' => 'Asin',
        'name' => '姓名',
        'remarks' => '模糊搜索备注'
    ];
    //星级
    public $starRatingRetention = [
//        ['label' => '0星', 'val' => 0],
        ['label' => '1星', 'val' => 1],
        ['label' => '2星', 'val' => 2],
        ['label' => '3星', 'val' => 3],
        ['label' => '4星', 'val' => 4],
        ['label' => '5星', 'val' => 5],
    ];

    //是否发送邮件
    public $sendEmailList = [
        ['label' => '是', 'val' => 1],
        ['label' => '否', 'val' => 0],
    ];

    //状态
    public $status = [
        0 => '买家未走完流程',
        1 => '待发送礼品',
        2 => '已发送礼品'
    ];

    //当前进度是否激活
    public $progressActivate = [
        1 => '已激活',
        2 => '激活异常'
    ];

    //当前进度是否激活 前端展示用 0:待激活,1:已激活,2:激活异常,3:激活失败
    public $progressActivateHtml = [
        0 => '待激活',
        1 => '已激活',
        2 => '激活异常',
        3 => '激活失败',
    ];

    public $templateField = [
        'order_name' => '[用户名]',
        'order_id' => '[订单号]',
        'take_over_address' => '[收货地址]',
        'gift_name' => '[礼品名称]',
        'product_title' => '[产品名称]',
        'purchase_time' => '[购买时间]',
        'activate_time' => '[激活成功时间]',
        'remarks' => '[评价内容]',
        'comment_link' => '[留评链接]',
        'bank_link' => '[回访链接]'
    ];

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new ActivateUserManagementModel();
    }

    /**
     * @Notes:获取搜索条件配置
     * @Interface activateConfig
     * @author: wuyu
     * @Time: 2023/5/5   11:06
     */
    public function activateConfig()
    {

        $config = [];
        $OrderAndCustomersOrderService = new OrderAndCustomersOrderService();
        $config['search_field_list'] = $this->searchField;
        $config['star_rating_list'] = $this->starRatingRetention;
        $config['send_email_list'] = $this->sendEmailList;
        $config['user_type_list'] = (new EmailTemplateModel())->userType;
        $config['progress_activate_list'] = $this->progressActivateHtml;
        $config['country_list'] = $OrderAndCustomersOrderService->country;
        $config['account_list'] = RedisService::getAccountList();
        $config['category_list'] = RedisService::getCategoryList();
        //获取标签
        $TagManageModel = new TagManageModel();
        $config['tag_list'] = $TagManageModel
            ->where('status', '=', 1)
            ->where('mark', '=', 1)
            ->whereIn('tag_type', [1, 2])
            ->get()->toArray();

        //获取品牌
        $config['brand_list'] = $OrderAndCustomersOrderService->brandList;
        //获取状态
//        $config['status_list'] = $this->progressActivate;

        return message("操作成功", true, $config);

    }

    /**
     * @Notes:列表获取数据
     * @Interface getList
     * @return array
     * @author: wuyu
     * @Time: 2023/5/5   10:12
     */
    public function getList()
    {
        $param = request()->all();
        // 查询条件
        $map[] = ['m.mark', '=', 1];
        // 搜索字段
        $progressActivate = getter($param, 'progress_activate', 1000);
        $searchField = getter($param, 'search_field', '');
        $searchValue = getter($param, 'search_value', '');
        $tag = getter($param, 'tag', []);
        $categoryName = getter($param, 'category_name', []);
        $activateTime = getter($param, 'activate_time', []);
        $purchaseTime = getter($param, 'purchase_time', []);
        $progressActivateSelect = getter($param, 'progress_activate_select', '');
        $country = getter($param, 'country', []);
        $account = getter($param, 'account', []);
        $ip = getter($param, 'ip', '');
        $referrer = getter($param, 'referrer', '');
        $brandCode = getter($param, 'brand_code', '');
        $page_size = getter($param, 'page', 1);
        $limit = getter($param, 'limit', 10);
        $sort = getter($param, 'sort', 'create_time');
        $order = getter($param, 'order', 'desc');

        if (!empty($activateTime)) {
            if (!empty($activateTime[0])) $map[] = ['m.activate_time', '>=', $activateTime[0]];
            if (!empty($activateTime[1])) $map[] = ['m.activate_time', '<=', $activateTime[1]];
        }
        if (!empty($purchaseTime)) {
            if (!empty($purchaseTime[0])) $map[] = ['m.purchase_time', '>=', $purchaseTime[0]];
            if (!empty($purchaseTime[1])) $map[] = ['m.purchase_time', '<=', $purchaseTime[1]];
        }
        if (!empty($progressActivate) && $progressActivate != 1) $map[] = ['m.progress_activate', '=', $progressActivate];
        if (isset($param['progress_activate_select'])) $map[] = ['m.progress_activate', '=', $progressActivateSelect];


        if ($progressActivate == 1 && empty($param['status'])) {
            $map[] = ['m.progress_activate', '>=', 1];
            $map[] = ['m.progress_activate', '<=', 2];
        }

        /*
            中低评分用户  匹配客户给了0~3星 并且没有给评价
            高评分用户 匹配客户给了3星以上 可以有评价内容也可以没有评价内容
            高评价已匹配用户 匹配客户给了好评论 并且匹配到在amazon留评
            高评价未匹配用户  匹配客户给了好评论 并且未匹配到在amazon留评
            中差评用户  匹配客户给了0~3星 并且给了评价
         */

//        if (!empty($progressActivateSelect)) $map[] = ['progress_activate', '=', $progressActivateSelect];
        if (isset($param['star_rating'])) $map[] = ['m.evaluate_star_rating', '=', $param['star_rating']];
        if (isset($param['send_email'])) $map[] = ['m.alerady_send_auto_email', '=', $param['send_email']];
        if (isset($param['status'])) {
            if ($param['status'] == EmailTemplateModel::TEMPLATE_TYPE_ACTIVATE) {//注册用户
                $map[] = ['m.progress_activate', '=', 1];
            } elseif ($param['status'] == EmailTemplateModel::TEMPLATE_TYPE_NO_COMMENT) {//选择礼品但未留评用户
                $confirmGift = $this->model->where('progress_confirm_gift', '=', 1)->get(['id'])->toArray();
                $confirmGiftIds = array_column($confirmGift, 'id');
                if (!empty($confirmGiftIds)) {
                    $ActivateUserManagementInfoModel = new ActivateUserManagementInfoModel();
                    $infoData = $ActivateUserManagementInfoModel->whereIn('activate_user_id', $confirmGiftIds)->where('comment', '!=', '')->get(['activate_user_id'])->toArray();
                    $activateIds = array_column($infoData, 'activate_user_id');
                    if (!empty($activateIds)) {
                        $map[] = ['id', 'in', $activateIds];
                        $map[] = ['evaluate_star_rating', '=', 0];
                    }
                }
            } elseif ($param['status'] == EmailTemplateModel::TEMPLATE_TYPE_LOW_RATING) { //中低评分用户  匹配客户给了0~3星 并且没有给评价
                $map[] = ['m.evaluate_star_rating', '>', 0];
                $map[] = ['m.evaluate_star_rating', '<=', 3];
                $map[] = ['m.progress_bad_reviews', '=', 0];
            } elseif ($param['status'] == EmailTemplateModel::TEMPLATE_TYPE_HEIGHT_RATING) { //高评分用户  匹配客户给了3星以上 可以有评价内容也可以没有评价内容
                $map[] = ['m.evaluate_star_rating', '>', 3];
//                $map[] = ['m.progress_favorable_comment', '=', 0];
            } elseif ($param['status'] == EmailTemplateModel::TEMPLATE_TYPE_HEIGHT_RATING_YES) { //高评价已匹配用户  匹配客户给了好评论 并且匹配到在amazon留评
                $map[] = ['m.progress_favorable_comment', '=', 1];
                $map[] = ['m.progress_favorable_comment_jump_amazon', '=', 1];
                $map[] = ['m.comment_retention_results', '=', 1];
            } elseif ($param['status'] == EmailTemplateModel::TEMPLATE_TYPE_HEIGHT_RATING_NO) { //高评价未匹配用户  匹配客户给了好评论 并且未匹配到在amazon留评
                $map[] = ['m.progress_favorable_comment', '=', 1];
                $map[] = ['m.progress_favorable_comment_jump_amazon', '=', 1];
                $map[] = ['m.comment_retention_results', '=', 0];
            } elseif ($param['status'] == EmailTemplateModel::TEMPLATE_TYPE_BAD_REVIEWS) { //中差评用户  匹配客户给了0~3星 并且给了评价
                $map[] = ['m.evaluate_star_rating', '>', 0];
                $map[] = ['m.evaluate_star_rating', '<=', 3];
                $map[] = ['m.progress_bad_reviews', '=', 1];
            }
//            elseif($param['status'] == EmailTemplateModel::TEMPLATE_TYPE_FAVORABLE_COMMENT){ //好评用户
//                $map[] = ['m.progress_favorable_comment', '=', 1];
//                $map[] = ['m.progress_favorable_comment_jump_amazon', '=', 0];
//            }
        }
        if (!empty($brandCode)) $map[] = ['m.brand_code', '=', $brandCode];
        if (!empty($ip)) $map[] = ['s.ip', '=', $ip];
        if (!empty($referrer)) $map[] = ['s.referrer', 'like', "%{$referrer}%"];

        $mainTable = $this->model->getTable();
        $VisitorsRecordModel = new VisitorsRecordModel();
        $sonTable = $VisitorsRecordModel->getTable();

        $model2 = $this->model::from("$mainTable as m")
            ->select('m.id')
            ->leftJoin("$sonTable as s", 's.id', '=', 'm.record_id')
            ->distinct('m.id')
            ->where($map);


        $ActivateUserManagementTagModel = new ActivateUserManagementTagModel();
        //权限过滤
//        $createUserAuth = CommonService::userAuth();
        $skuAuth = CommonService::skuAuth();

        $tagArr = $categoryArr = [];
        if (!empty($tag)) {
            $ActivateTagList = $ActivateUserManagementTagModel->whereIn('tag_manage_id', $tag)->groupBy('activate_user_id')->get('activate_user_id')->toArray();
            if (!empty($ActivateTagList)) {
                $tagArr = array_column($ActivateTagList, 'activate_user_id');
            }else{
                $tagArr = [-1];
            }
        }
        $ActivateUserManagementInfoModel = new ActivateUserManagementInfoModel();
        if (!empty($categoryName)) {
            $categoryList = $ActivateUserManagementInfoModel->whereIn('product_category_name', $categoryName)->get('activate_user_id')->toArray();
            if (!empty($categoryList)) {
                $categoryArr = array_column($categoryList, 'activate_user_id');
            }else{
                $categoryArr = [-1];
            }
        }
        $activateUserIds = array_merge($tagArr, $categoryArr);

        $offset = ($page_size - 1) * $limit;
//        $model2 = $this->model->where($map);

        $model = $this->model::from("$mainTable as m")
            ->select('m.*')
            ->leftJoin("$sonTable as s", 's.id', '=', 'm.record_id')
            ->distinct(true)
            ->where($map);

        if (!empty($skuAuth) && $progressActivate != 3) {
            $model2->whereIn('m.platform_sku', $skuAuth);
            $model->whereIn('m.platform_sku', $skuAuth);
        }
        if (!empty($activateUserIds)) {
            $model2->whereIn('m.id', $activateUserIds);
            $model->whereIn('m.id', $activateUserIds);
        }

        if (!empty($createUserAuth) && $progressActivate == 3) {
            //获取自己负责的品牌
            $CommentGuideLinkModel = new CommentGuideLinkModel();
            $CommentGuideLinkUserModel = new CommentGuideLinkUserModel();
            $CommentGuideLinkTable = $CommentGuideLinkModel->getTable();
            $CommentGuideLinkUserTable = $CommentGuideLinkUserModel->getTable();
            $urlList = $this->model::from("$CommentGuideLinkTable as m")
                ->select('m.url')
                ->leftJoin("$CommentGuideLinkUserTable as s", 's.guide_link_id', '=', 'm.id')
                ->distinct(true)
                ->where('s.user_id', '=', $this->model->userId)->get()->toArray();
            $urlArr = [];
            foreach ($urlList as $url) {
                $urlArr[] = 'https://' . $url['url'] . '/activate';
            }
            if (!empty($urlArr)) {
                $model->whereIn('s.referrer', $urlArr);
                $model2->whereIn('s.referrer', $urlArr);
            }

        }

        if (!empty($searchField) && !empty($searchValue)) {
            $searchValue = str_replace(['；', ',', '，', "\r\n", "\r", "\n"], ';', $searchValue);
            $searchValueArr = explode(';', $searchValue);
            if ($searchField == 'remark') {
                $model->where('m.' . $searchField, 'like', "%{$searchValue}%");
                $model2->where('m.' . $searchField, 'like', "%{$searchValue}%");
            } else {
                $model->whereIn('m.' . $searchField, $searchValueArr);
                $model2->whereIn('m.' . $searchField, $searchValueArr);
            }
        }

        if (!empty($country)) {
            $model->whereIn('m.order_country', $country);
            $model2->whereIn('m.order_country', $country);
        }
        if (!empty($account)) {
            $model->whereIn('m.account', $account);
            $model2->whereIn('m.account', $account);
        }

        $count = $model2->count();
        $list = $model
            ->orderBy($sort, $order)
            ->offset($offset)
            ->limit(PERPAGE)
            ->get()->toArray();
//        $list = $this->model->getList($map, [['create_time', 'desc']],"{$offset},{$limit}");
//        $count = $this->model->where($map)->count();

        //获取访客信息记录
        $recordIds = $infoList = [];
        $tagGroupList = $emailSendList = [];
        if (!empty($list)) {
            $recordIds = array_column($list, 'record_id');
            $ids = array_column($list, 'id');
            $VisitorsRecordModel = new VisitorsRecordModel();
            $recordList = $VisitorsRecordModel->whereIn('id', $recordIds)->get()->toArray();
            $recordCol = array_column($recordList, null, 'id');

            //获取客户关联的标签
            $TagManageModel = new TagManageModel();
            $mainTable = $ActivateUserManagementTagModel->getTable();
            $sonTable = $TagManageModel->getTable();
            $tagList = $ActivateUserManagementTagModel::from("$mainTable as m")
                ->select(['m.*', 's.tag_name', 's.tag_color'])
                ->join("$sonTable as s", 's.id', '=', 'm.tag_manage_id')
                ->whereIn('m.activate_user_id', $ids)->get()->toArray();

            foreach ($tagList as $vv) {
                $tagGroupList[$vv['activate_user_id']][] = $vv;
            }

            //获取邮件发送总数量
            $SendLogModel = new SendLogModel();
            $emailData = $SendLogModel
                ->whereIn('status', [SendLogService::STATUS_SEND_SUCCESS, SendLogService::STATUS_OPEN, SendLogService::STATUS_CLICK_LINK])
                ->whereIn('activate_id', $ids)
                ->get(['id', 'activate_id'])
                ->toArray();
            foreach ($emailData as $emailV) {
                $emailSendList[$emailV['activate_id']][] = $emailV;
            }

            //获取扩展字段信息
            $infoArr = $ActivateUserManagementInfoModel->whereIn('activate_user_id', $ids)->get()->toArray();
            $infoList = array_column($infoArr, null, 'activate_user_id');
        }

        $accountList = RedisService::getAccountList();
        $accountCol = array_column($accountList, 'platform_user_name', 'user_account');

        //获取用户信息
        $UserModel = new UserModel();
        $userList = $UserModel->where('status', '=', 1)->get(['id', 'realname'])->toArray();
        $userListCol = array_column($userList, 'realname', 'id');

        foreach ($list as $kk => $val) {
            $val['record_list'] = $recordCol[$val['record_id']] ?? [];
            $infoV = $infoList[$val['id']] ?? [];
            unset($infoV['id']);
            $val = array_merge($val, $infoV);
            //处理礼品图片
            if (!empty($val['gift_image'])) $val['gift_image'] = IMG_URL . ($val['gift_image'] ?? '');

            $val['evaluate_star_rating'] = $val['evaluate_star_rating'] . '星';
            if (!empty($val['record_list']['create_time'])) $val['record_list']['create_time'] = date("Y-m-d H:i:s", $val['record_list']['create_time']);
            $val['tag_list'] = $tagGroupList[$val['id']] ?? [];
            $val['account'] = $accountCol[$val['account']] ?? [];
            if (!empty($emailSendList[$val['id']])) {
                $val['send_email_count'] = count($emailSendList[$val['id']]);
            }

            $val['create_user_name'] = $userListCol[$val['create_user']] ?? '';

            //用户类型
            $val['user_type_html'] = '';
            if (!empty($val['progress_favorable_comment'])) {
                $val['user_type_html'] = '好评用户';
            } elseif (!empty($val['progress_bad_reviews'])) {
                $val['user_type_html'] = '中差评用户';
            } elseif (!empty($val['progress_star_rating_evaluation'])) {
                if ($val['evaluate_star_rating'] >= 4) {
                    $val['user_type_html'] = '高评分用户';
                } else {
                    $val['user_type_html'] = '中低评分用户';
                }
            } elseif (!empty($val['progress_confirm_gift'])) {
                $val['user_type_html'] = '选择礼品但未留评用户';
            } else {
                $val['user_type_html'] = '注册用户';
            }

            $val['progress_activate_html'] = $this->progressActivateHtml[$val['progress_activate']] ?? '';

            $list[$kk] = $val;
        }

        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );

    }


    /**
     * @Notes:手动结束进度
     * @Interface handEndProgress
     * @author: wuyu
     * @Time: 2023/5/4   18:53
     */
    public function handEndProgress()
    {
        $param = request()->all();
        $id = $param['id'] ?? 0;
        $data = [
            'status' => 2,
            'progress_activate' => 1,
            'progress_confirm_gift' => 1,
            'progress_appraise' => 1,
            'progress_guide_appraise' => 1,
            'customer_confirm_for_review' => 2,
            'comment_retention_results' => 1,
            'progress_submit_receiving_information' => 1,
            'update_time' => time(),
            'update_user' => JwtUtils::getUserId(),
        ];
        $result = $this->model->where('id', '=', $id)->update($data);
        if (empty($result)) {
            return message("操作失败", false);
        } else {
            $this->model->cacheReset($id, $data, $id);
            return message("操作成功", true, []);
        }

    }

    /**
     * @Notes:匹配当前也留评信息
     * @Interface matchCommentInfo
     * @param $param
     * @return array
     * @author: wuyu
     * @Time: 2023/5/27   11:34
     */
    public function matchCommentInfo()
    {
        try {
            //匹配评论
            $param = request()->all();
            $ids = $param['ids'] ?? [];
            if (empty($ids)) throw new \Exception('非法ID');

            $ActivateUserManagementInfoModel = new ActivateUserManagementInfoModel();
            $mainTable = $this->model->getTable();
            $infoTable = $ActivateUserManagementInfoModel->getTable();

            $activateData = $this->model::from("$mainTable as m")
                ->join("$infoTable as s", 's.activate_user_id', '=', 'm.id')
                ->where('s.comment', '!=', '')
                ->where('m.mark', '=', 1)
                ->whereIn('m.id', $ids)
                ->get(['m.id', 'm.name', 'm.asin', 'm.evaluate_star_rating', 'm.activate_time', 's.comment'])
                ->toArray();

            if (empty($activateData)) throw new \Exception('当前记录没有5星评论');
            $activateMap = [];
            $activateCol = array_column($activateData, 'asin');
            foreach ($activateData as $activateV) {
                $activateMap[$activateV['asin']][] = $activateV;
            }

            $EvaluationMonitoringModel = new EvaluationMonitoringModel();
            $EvaluationMonitorConnectModel = new EvaluationMonitorConnectModel();
            $mainTable = $EvaluationMonitoringModel->getTable();
            $sonTable = $EvaluationMonitorConnectModel->getTable();

            $monitoringList = $EvaluationMonitoringModel::from("$mainTable as m")
                ->select(['m.id', 'm.asin', 's.id as evaluation_id', 's.evaluation_connent', 's.evaluation_time', 's.evaluation_title', 's.stars', 's.evaluation_user'])
                ->join("$sonTable as s", 's.evaluation_monitor_id', '=', 'm.id')
                ->whereIn('m.asin', $activateCol)->get()->toArray();
            if (empty($monitoringList)) throw new \Exception('当前记录没有amazon评论');

            $monitoringMap = [];
            foreach ($monitoringList as $monitoringV) {
                $monitoringMap[$monitoringV['asin']][] = $monitoringV;
            }
            $matchCommentData = [];
            $weekDay = 7 * 24 * 60 * 60;
            foreach ($activateData as $activateDataV) {
                $map = $monitoringMap[$activateDataV['asin']] ?? [];
                foreach ($map as $vv) {
                    $percent = $this->similarPercent($activateDataV, $vv);

                    $activate_time = $activateDataV['activate_time'];//2023-6-10
                    $evaluation_tim = $vv['evaluation_time'];
                    $activate_time_s = strtotime($activate_time);
                    $evaluation_tim_s = strtotime($evaluation_tim);
                    $diff = $activate_time_s - $evaluation_tim_s;

                    if ($percent >= 40 && $diff <= $weekDay && $diff > 0) $matchCommentData[$activateDataV['id']][] = [
                        'evaluation_id' => $vv['evaluation_id'],
                        'percent' => intval($percent)
                    ];
                }
            }

        } catch (\Exception $e) {
            return message("操作失败:" . $e->getMessage(), false);
        }

        return message("操作成功", true, $matchCommentData);
    }


    /**
     * @Notes:计算相似度
     * @Interface similarPercent
     * @param $activateData //激活买家管理数据
     * @param $monitorData //评价监控数据
     * @return int
     * @author: wuyu
     * @Time: 2023/5/27   14:09
     */
    public function similarPercent($activateData, $monitorData)
    {

        $percents = 0;
        $activateComment = $activateData['comment'] ?? '';//买家激活内容
        $monitorTitle = $monitorData['evaluation_title'] ?? '';//amazon评论标题
        $monitorConnent = $monitorData['evaluation_connent'] ?? '';//amazon评论内容
        $name = $activateData['name'] ?? ''; //买家激活姓名
        $evalutionUser = $monitorData['evaluation_user'] ?? ''; //amazon评论用户
        $activateTime = $activateData['activate_time'] ?? ''; //买家激活时间
        $evalutionTime = $monitorData['evaluation_time'] ?? ''; //amazon评论时间
        $starRating = $activateData['evaluate_star_rating'] ?? 0; //买家评论星级
        $evalutionStar = $activateData['stars'] ?? 0; //买家评论星级
        #评价和amazon标题完全匹配 相似度置为100%
        similar_text($activateComment, $monitorTitle, $percent1);
        if ($percent1 >= 60) return $percent1;
        #评价和amazon内容完全匹配 相似度置为100%
        similar_text($activateComment, $monitorConnent, $percent2);
        if ($percent2 >= 60) return $percent2;
        #姓名相似度超过50% 取对应的相似度
        similar_text($name, $evalutionUser, $percentUser);
        if ($percentUser >= 50) return $percentUser;
        #姓名+评价日期+星级一样  相似度置为100%
//        similar_text($name, $evalutionUser, $percentUser);
//        $activateTime = date("Y-m-d",strtotime($activateTime));
//        $diffTime = $this->diffBetweenTwoDays($activateTime,$evalutionTime);
//        if ($percentUser >=50 && $diffTime <=2 && $starRating == intval($evalutionStar)){
//            return 100;
//        }


        return $percents;

    }


    /**
     * 求两个日期之间相差的天数
     * (针对1970年1月1日之后，求之前可以采用泰勒公式)
     * @param string $day1
     * @param string $day2
     * @return number
     */
    function diffBetweenTwoDays($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }


    /**
     * @Notes:修改备注
     * @Interface submitRemarks
     * @author: wuyu
     * @Time: 2023/5/5   10:11
     */
    public function submitRemarks()
    {
        $param = request()->all();
        $id = $param['id'] ?? 0;
        $remarks = $param['remarks'] ?? '';
        $data = [
            'remarks' => $remarks
        ];
        $result = $this->model->where('id', '=', $id)->update($data);
        if (empty($result)) {
            return message("操作失败", false);
        } else {
            $this->model->cacheReset($id, $data, $id);
            return message("操作成功", true, []);
        }
    }

    public function getEdmTemplate()
    {
        $EmailTemplateModel = new EmailTemplateModel();
        $templateList = $EmailTemplateModel->where('mark', '=', 1)->get(['id', 'name'])->toArray();
        return message("操作成功", true, $templateList);
    }

    /**
     * @Notes:获取系统评价信息
     * @Interface getMatchDetail
     * @return array
     * @author: wuyu
     * @Time: 2023/5/27   17:44
     */
    public function getMatchDetail()
    {
        $param = request()->all();
        $activateId = $param['id'] ?? '';
        $matchCommentList = $param['match_comment_list'] ?? [];
        //获取激活买家信息
        $activateInfo = $this->model->getOne([
            ['id', "=", $activateId],
        ], 'id,name,email,evaluate_star_rating,activate_time,comment_retention_results');

        if (empty($activateInfo)) return message("操作失败:数据不存在", false);

        $ActivateUserManagementInfoModel = new ActivateUserManagementInfoModel();
        $infoData = $ActivateUserManagementInfoModel->getOne([
            ['activate_user_id', '=', $activateId]
        ], 'take_over_name,take_over_email,comment,similarity,retention_monitor_connect_id', false, false);
        $activateInfo = array_merge($activateInfo, $infoData);

        if ($activateInfo['comment_retention_results'] == 1) {
            $matchCommentList = [
                ['evaluation_id' => $activateInfo['retention_monitor_connect_id'] ?? '',
                    'percent' => $activateInfo['similarity'] ?? ''
                ]
            ];
        }

        //获取匹配结果
        $evaluationIds = array_column($matchCommentList, 'evaluation_id');
        $EvaluationMonitorConnectModel = new EvaluationMonitorConnectModel();
        $monitorConnectData = $EvaluationMonitorConnectModel->whereIn('id', $evaluationIds)->get()->toArray();
        $matchCommentCol = array_column($matchCommentList, null, 'evaluation_id');
        foreach ($monitorConnectData as $key => $val) {
            $monitorConnectData[$key]['percent'] = $matchCommentCol[$val['id']]['percent'] ?? '';
            $monitorConnectData[$key]['stars'] = intval($val['stars']) . '星';
        }

        return message("操作成功", true, ['monitor_list' => $monitorConnectData, 'activate_info' => $activateInfo]);
    }


    /** 添加标签
     * @Notes:
     * @Interface addTag
     * @author: wuyu
     * @Time: 2023/5/10   18:25
     */
    public function addTag()
    {
        try {
            $param = request()->all();
            $id = $param['id'] ?? 0;
            $tagIds = $param['tag_ids'] ?? [];
            if (empty($tagIds)) throw new \Exception('请至少选择一个标签');

            $ActivateUserManagementTagModel = new ActivateUserManagementTagModel();
            $ActivateUserManagementTagModel->where('activate_user_id', $id)->delete();
            foreach ($tagIds as $val) {
                $data = [
                    'activate_user_id' => $id,
                    'tag_manage_id' => $val
                ];
                $ActivateUserManagementTagModel->insert($data);
            }
            return message("操作成功", true, []);
        } catch (\Exception $e) {
            return message("操作失败", false, $e->getMessage());
        }

    }

    /**
     * @Notes:批量添加标签
     * @Interface addTagBatch
     * @author: wuyu
     * @Time: 2023/6/14   17:50
     */
    public function addTagBatch()
    {
        try {
            $param = request()->all();
            $customerIds = $param['customer_ids'] ?? [];
            $tagIds = $param['tag_ids'] ?? [];
            if (empty($customerIds)) throw new \Exception('请至少选择一条数据');
            if (empty($tagIds)) throw new \Exception('请至少选择一个标签');

            $ActivateUserManagementTagModel = new ActivateUserManagementTagModel();
            foreach ($customerIds as $id) {
                foreach ($tagIds as $val) {
                    //判断是否存在
                    $exists = $ActivateUserManagementTagModel->getOne([
                        ['activate_user_id', '=', $id],
                        ['tag_manage_id', '=', $val]
                    ]);
                    if (!empty($exists)) continue;
                    $data = [
                        'activate_user_id' => $id,
                        'tag_manage_id' => $val
                    ];
                    $ActivateUserManagementTagModel->insert($data);
                }
            }

            return message("操作成功", true, []);
        } catch (\Exception $e) {
            return message("操作失败", false, $e->getMessage());
        }
    }


    /**
     * @Notes:系统评价信息 确认匹配
     * @Interface confirmMate
     * @author: wuyu
     * @Time: 2023/5/31   14:15
     */
    public function confirmMate()
    {

        try {
            $param = request()->all();
            $activateId = $param['activate_id'] ?? 0;
            $monitorConnectId = $param['monitor_connect_id'] ?? 0;
            $percent = $param['percent'] ?? '';
            if (empty($activateId) || empty($monitorConnectId)) {
                throw new \Exception('参数不正确');
            }

            $mateData = [
                'comment_retention_results' => 1,
//                'retention_monitor_connect_id'=>$monitorConnectId,
//                'similarity'=>$percent
            ];
            $result = $this->model->where('id', '=', $activateId)->update($mateData);
            if (empty($result)) {
                throw new \Exception('记录操作失败');
            } else {
                $ActivateUserManagementInfoModel = new ActivateUserManagementInfoModel();
                $ActivateUserManagementInfoModel
                    ->where('activate_user_id', '=', $activateId)
                    ->update(['retention_monitor_connect_id' => $monitorConnectId, 'similarity' => $percent]);
                $this->model->cacheReset($activateId, $mateData, $activateId);
            }

            return message("操作成功", true, []);

        } catch (\Exception $e) {
            return message("操作失败", false, $e->getMessage());
        }

    }


    /**
     * @Notes:激活失败 匹配激活成功
     * @Interface matchActivateSuccess
     * @author: wuyu
     * @Time: 2023/7/10   14:17
     */
    public function matchActivateSuccess()
    {
        try {
            $param = request()->all();
            $ids = $param['ids'] ?? [];
            if (empty($ids)) throw new Exception('Id格式不正确');
            //获取订单
            $OrderAndCustomersOrderModel = new OrderAndCustomersOrderModel();
            $OrderAndCustomersOrderDetailModel = new OrderAndCustomersOrderDetailModel();
            $OrderAndCustomersOrderExtendModel = new OrderAndCustomersOrderExtendModel();
            $ActivateUserManagementInfoModel = new ActivateUserManagementInfoModel();
            $GiftModel = new GiftModel();
            $GiftPlatformSkuModel = new GiftPlatformSkuModel();
//            $UserAccountModel = new UserAccountModel();
            $orderMsg = [];
            foreach ($ids as $id) {
                $activateData = $this->model->getOne([
                    ['id', '=', $id]
                ]);
                if (empty($activateData)) continue;
                $orderData = $OrderAndCustomersOrderModel->getOne([
                    ['order_id', '=', $activateData['order_id']]
                ], '*', false, false);
                if (empty($orderData)) {
                    $orderMsg[] = '订单id: ' . $activateData['order_id'] . '不存在';
                    continue;
                }
                $detailData = $OrderAndCustomersOrderDetailModel->getOne([
                    ['order_id', '=', $orderData['id']]
                ], '*', false, false);

//                $userAccountData = $UserAccountModel->getOne([
//                    ['account_name', '=', $orderData['user_account']]
//                ], '*', false, false);

                $progressActivate = 2;
                if (!empty($detailData['platform_sku'])) {
                    $mainTable = $GiftModel->getTable();
                    $sonTable = $GiftPlatformSkuModel->getTable();
                    $giftInfo = $GiftModel::from("$mainTable as m")
                        ->select('m.*')
                        ->join("$sonTable as s", 's.gift_id', '=', 'm.id')
                        ->distinct(true)
//                        ->where(['m.create_user' => $userAccountData['user_group_id']])
                        ->where(['m.status' => 1])
                        ->where(['m.mark' => 1])
                        ->where(['s.platform_sku' => $detailData['platform_sku']])
                        ->limit(3)
                        ->get()
                        ->toArray();
                    if (!empty($giftInfo)) $progressActivate = 1;
                }

                $mainData = [
                    'asin' => $detailData['asin'] ?? '',
                    'brand_code' => $detailData['brand_code'] ?? '',
                    'platform_sku' => $detailData['platform_sku'] ?? '',
                    'account' => $orderData['user_account'] ?? '',
                    'progress_activate' => $progressActivate,
                    'order_country' => $orderData['country_code'] ?? ''
                ];

                $this->model->where('id', '=', $id)->update($mainData);

                $infoData = [
                    'activate_user_id' => $id,
                    'product_title' => $detailData['product_title'] ?? '',
                    'all_price' => $orderData['amount_paid'] ?? 0.0,
                    'discount' => $orderData['discount_val'] ?? 0.0,
                    'product_category_name' => $detailData['product_category_name1'] ?? ''
                ];

                $infoExists = $ActivateUserManagementInfoModel->getOne([
                    ['activate_user_id', '=', $id]
                ], '*', false, false);
                if (!empty($infoExists)) {
                    $ActivateUserManagementInfoModel->where('activate_user_id', '=', $id)->update($infoData);
                } else {
                    $ActivateUserManagementInfoModel->insert($infoData);
                }
                $this->model->cacheReset($id, [], $id); //清除缓存
            }

            if (!empty($orderMsg)) {
                $msg = implode('</br>', $orderMsg);
                throw new \Exception($msg);
            }

            return message("操作成功", true, []);

        } catch (\Exception $e) {
            return message($e->getMessage(), false);
        }

    }


    /**
     * @Notes:发送邮件
     * @Interface sendEmail
     * @author: wuyu
     * @Time: 2023/5/5   16:45
     */
    public function sendEmail()
    {

        $param = request()->all();
        $ids = $param['ids'] ?? [];
        $dataInfo = [
            'edm_template' => $param['edm_template'] ?? '',
            'content' => $param['content'] ?? '',
            'title' => $param['title'] ?? '',
            'return_receive_email' => $param['return_receive_email'] ?? '',
            'send_email_type' => SendLogService::SEND_EMAIL_TYPE_HAND,
            'date_time' => $param['date_time'] ?? ''
        ];
        $ActivateUserManagementModel = new ActivateUserManagementModel();
        $err = '';
        foreach ($ids as $id) {
            $dataInfo['id'] = $id;
            $responseData = $this->emailService($dataInfo);
            if ($responseData['code'] == 1) {
                $err .= $responseData['message'] . '</br>';
            } else {
                $ActivateUserManagementModel->where('id', '=', $id)->update(['alerady_send_auto_email' => 1]);
            }
        }
        if (!empty($err)) return message("操作失败:" . $err, false);
        return message("操作成功", true, []);
    }


    /**
     * 发送邮件逻辑处理层
     * @Notes:
     * @Interface emailService
     * @author: wuyu
     * @Time: 2023/5/31   18:35
     */
    public function emailService($param)
    {
        $SendLogService = new SendLogService();
        $SendLogModel = new SendLogModel();
        try {
            //获取模板信息
            $id = $param['id'] ?? 0;
            $edmTemplateId = $param['edm_template'] ?? 0;
            $sendEmailType = $param['send_email_type'] ?? 0;
            $title = $param['title'] ?? '';
            $returnReceiveEmail = $param['return_receive_email'] ?? '';
            $content = $param['content'] ?? '';
            $dateTime = $param['date_time'] ?? '';
            if (!empty($dateTime)) {
                $dateTime = date('Y-m-d H:i:s', strtotime($param['date_time']));
                $ActivateUserManagementEmailModel = new ActivateUserManagementEmailModel();
                $ActivateInfo = [
                    'activate_user_id' => $id,
                    'title' => $title,
                    'content' => $content,
                    'date_time' => $dateTime,
                    'create_user' => $ActivateUserManagementEmailModel->userId,
                    'create_time' => time()
                ];
                $infoId = $ActivateUserManagementEmailModel->insertGetId($ActivateInfo);
                if (empty($infoId)) return ['code' => 0, 'message' => '新增激活买家其他信息失败'];
                return ['code' => 0, 'message' => '操作成功'];
            }

            if (empty($edmTemplateId) && empty($content)) {
                throw new \Exception('请选择模板 或 选择自定义内容');
            }
//            if (empty($edmTemplateId) && empty($returnReceiveEmail) ){
//                throw new \Exception('请选择接收方邮箱,否则客户无法回复邮件');
//            }
            if (!empty($edmTemplateId)) {
                $EmailTemplateModel = new EmailTemplateModel();
                $templateData = $EmailTemplateModel->getOne([
                    ['id', '=', $edmTemplateId],
                ]);

                if (empty($templateData)) throw new \Exception('emd模板不存在');
            } else {
                $templateData = [
                    'id' => $edmTemplateId,
                    'title' => $title,
                    'content' => $content
                ];
            }

            //获取激活客户信息
            $ActivateUserManagementModel = new ActivateUserManagementModel();
            $ActivateUserManagementInfoModel = new ActivateUserManagementInfoModel();
            $activateData = $ActivateUserManagementModel->getOne([
                ['id', '=', $id],
            ], 'id,name,email,order_id,purchase_time,activate_time,remarks,create_user,platform_sku');
            $infoData = $ActivateUserManagementInfoModel->getOne([
                ['activate_user_id', '=', $id]
            ], 'take_over_address,gift_name,order_name,product_title', false, false);
            $activateData = array_merge($activateData, $infoData);

            if (empty($activateData)) throw new \Exception('激活买家管理记录不存在');
            $templateField = array_flip($this->templateField);
            foreach ($templateField as $kk => $val) {
                if (isset($activateData[$val])) $templateData['title'] = str_replace($kk, $activateData[$val], $templateData['title']);
                if (isset($activateData[$val])) $templateData['content'] = str_replace($kk, $activateData[$val], $templateData['content']);
            }

            if (empty($returnReceiveEmail)) {
                $AutoEmailModel = new AutoEmailModel();
                $autoEmailOne = $AutoEmailModel->getOne([
                    ['template_id', '=', $templateData['id']],
                    ['status', '=', 1],
                    ['create_user', '=', $activateData['create_user']],

                ]);
                if (empty($autoEmailOne)) {
                    $UserEmailModel = new UserEmailModel();
                    $userEmailOne = $UserEmailModel->getOne([
                        ['user_id', '=', $activateData['create_user']]
                    ]);
                    if (!empty($userEmailOne)) $returnReceiveEmail = $userEmailOne['email_name'];
                } else {
                    $returnReceiveEmail = $autoEmailOne['email_name'];
                }
            }

            if (empty($returnReceiveEmail)) {
                throw new \Exception('创建用户对应的接收邮箱不存在,请前往【自动信管理】或【用户与邮箱配置】设置');
            }

            //记录发送日志
            $sendLogData = [
                'activate_id' => $id,
                'name' => $activateData['name'],
                'email' => $returnReceiveEmail,
                'order_id' => $activateData['order_id'],
                'status' => 1,
                'type' => $sendEmailType,
                'source' => $SendLogService::SEND_SOURCE_ACTIVATE,//激活买家管理
                'receive_email' => $activateData['email'],
                'title' => $templateData['title'],
                'sku' => $activateData['platform_sku'],
                'content' => $templateData['content'],
                'create_time' => time(),
                'create_user' => $activateData['create_user']
            ];
            $logId = $SendLogService->emailSendLog($sendLogData);

            //将日志内容特殊字符替换 https://www.warrantysystem.top:168/setVisitorsRecord?log_id=[日志id]
            $templateData['content'] = str_replace('[日志id]', $logId, $templateData['content']);
            $templateData['content'] = str_replace('<p><a', '<a', $templateData['content']);
            $templateData['content'] = str_replace('</a></p>', "</a>", $templateData['content']);
            $statusPrefix = 2;//状态前缀 进入下一个阶段用 假如邮件日志不是这个状态 可能手动修改 不进行操作
            $templateData['content'] = $templateData['content'] . '<img width="1px" height="1px" src="' . env('APP_URL') . '/v1/emailReady?status_prefix=' . $statusPrefix . '&log_id=' . $logId . '"  />';
            $emailParams = [
                'send_email' => $returnReceiveEmail,
                'receive_email' => $activateData['email'],
                'return_receive_email' => $returnReceiveEmail,
//                'email_pass'=>$userEmailOne['email_pass']
            ];
//            $sendEmail = $this->emailqq($templateData,$emailParams,$logId);
            $sendEmail = $this->emailoutlook($templateData, $emailParams, $logId);
            if ($sendEmail['code'] == 1) throw new \Exception($sendEmail['message']);
            //修改日志状态
            $SendLogService->updateById($logId, ['status' => 2, 'send_success_time' => time(), 'content' => $templateData['content']]);
            //修改为发送成功
            $ActivateUserManagementModel->where('id', '=', $id)->update(['alerady_send_auto_email' => 1]);
            $ActivateUserManagementModel->cacheReset($id, [], $id);

            return ['code' => 0, 'message' => '操作成功'];
//            $info = $this->emailoutlook();
//            Log::info($sendEmail);
        } catch (\Exception $e) {
            $msg = $e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine();
            $sendLogData['status'] = 5;
            $sendLogData['send_msg'] = $msg;
            //删除待发送的
            $SendLogModel->where('activate_id',$id)->where('status',1)->update(['mark'=>0]);
        }

        $SendLogService->emailSendLog($sendLogData);
        if ($sendLogData['status'] == 5) {
            return ['code' => 1, 'message' => '操作失败:' . $sendLogData['send_msg']];
        }
        return ['code' => 0, 'message' => '操作成功'];

    }


    /**
     * @Notes:激活买家管理 流程步骤触发邮件
     * @Interface autoSendEmail
     * @param $param
     * @return array
     * @author: wuyu
     * @Time: 2023/6/7   11:48
     */
    public function autoSendEmail($param)
    {
        $SendLogService = new SendLogService();
        $SendLogModel = new SendLogModel();
        try {
            //获取模板信息
            $id = $param['id'] ?? 0;
            $userId = $param['user_id'] ?? 0;
            $templateType = $param['template_type'] ?? 0;
            $source = $param['source'] ?? 0;
            $sendEmailType = $param['send_email_type'] ?? 0;
            $activateId = $param['activate_id'] ?? 0;
            $emailName = $param['email_name'] ?? '';

            //记录发送日志
            $sendLogData = [
                'activate_id' => $id,
                'status' => 1,
                'source' => $source,
                'type' => $sendEmailType,
                'create_user' => $userId,
                'create_time' => time(),
            ];

            //获取激活客户信息
            $ActivateUserManagementModel = new ActivateUserManagementModel();
            $ActivateUserManagementInfoModel = new ActivateUserManagementInfoModel();
            $activateData = $ActivateUserManagementModel->getOne([
                ['id', '=', $id],
            ], 'id,name,email,order_id,purchase_time,activate_time,remarks,create_user,platform_sku');
            $infoData = $ActivateUserManagementInfoModel->getOne([
                ['activate_user_id', '=', $id]
            ], 'take_over_address,gift_name,order_name,product_title', false, false);
            $activateData = array_merge($activateData, $infoData);

            if (empty($activateData)) throw new \Exception('激活买家管理记录不存在');

            $sendLogData['name'] = $activateData['name'];
            $sendLogData['order_id'] = $activateData['order_id'];
            $sendLogData['receive_email'] = $activateData['email'];

            //根据用户获取模板
            $EmailTemplateModel = new EmailTemplateModel();
            $templateData = $EmailTemplateModel->getOne([
                ['type', '=', $templateType],
                ['create_user', '=', $userId]
            ]);
            if (empty($templateData)) throw new \Exception('发送自动信对应的邮件模板不存在');

            $templateField = array_flip($this->templateField);
            foreach ($templateField as $kk => $val) {
                if (isset($activateData[$val])) $templateData['title'] = str_replace($kk, $activateData[$val], $templateData['title']);
                if (isset($activateData[$val])) $templateData['content'] = str_replace($kk, $activateData[$val], $templateData['content']);
            }

            if (empty($emailName)) {
                $UserEmailModel = new UserEmailModel();
                $userEmailOne = $UserEmailModel->getOne([
                    ['user_id', '=', $activateData['create_user']]
                ]);
                if (!empty($userEmailOne)) $emailName = $userEmailOne['email_name'];
            }

            if (empty($emailName)) throw new \Exception('创建用户对应的邮箱不存在');


            $sendLogData['title'] = $templateData['title'];
            $sendLogData['content'] = $templateData['content'];
            $sendLogData['email'] = $emailName;
            $sendLogData['sku'] = $activateData['platform_sku'];
            $sendLogData['create_user'] = $activateData['create_user'];

            $logId = $SendLogService->emailSendLog($sendLogData);
            //将日志内容特殊字符替换
            $templateData['content'] = str_replace('[日志id]', $logId, $templateData['content']);
            $templateData['content'] = str_replace('<p><a', '<a', $templateData['content']);
            $templateData['content'] = str_replace('</a></p>', "</a>", $templateData['content']);
            $statusPrefix = 2;//状态前缀 进入下一个阶段用 假如邮件日志不是这个状态 可能手动修改 不进行操作
            $templateData['content'] = $templateData['content'] . '<img width="1px" height="1px" src="' . env('APP_URL') . '/v1/emailReady?status_prefix=' . $statusPrefix . '&log_id=' . $logId . '"  />';
            $emailParams = [
                'send_email' => $emailName,
                'receive_email' => $activateData['email'],
            ];
//            $sendEmail = $this->emailqq($templateData,$emailParams,$logId);
            $sendEmail = $this->emailoutlook($templateData, $emailParams, $logId);
            if ($sendEmail['code'] == 1) throw new \Exception($sendEmail['message']);
            //修改日志状态
            $SendLogService->updateById($logId, ['status' => 2, 'send_success_time' => time(), 'content' => $templateData['content']]);
            $SendLogModel->cacheReset($logId, [], $logId);
            //修改为发送成功
            $ActivateUserManagementModel->where('id', '=', $id)->update(['alerady_send_auto_email' => 1]);

            return ['code' => 0, 'message' => '操作成功'];
        } catch (\Exception $e) {
            $msg = $e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine();
            $sendLogData['status'] = 5;
            $sendLogData['send_msg'] = $msg;
            //删除待发送的
            $SendLogModel->where('activate_id',$id)->where('status',1)->update(['mark'=>0]);
        }

        $SendLogService->emailSendLog($sendLogData);
        if ($sendLogData['status'] == 5) {
            return ['code' => 1, 'message' => '操作失败:' . $sendLogData['send_msg']];
        }
        return ['code' => 0, 'message' => '操作成功'];

    }


    /**
     * @Notes:发送qq邮件
     * @Interface emailqq
     * @param $templateData
     * @param $sendEmail
     * @param $receiveEmail
     * @return array
     * @throws \PHPMailer\PHPMailer\Exception
     * @author: wuyu
     * @Time: 2023/5/15   15:58
     */
    public function emailqq($templateData, $emailParams, $logId = 0)
    {
        $sendEmail = $emailParams['send_email'] ?? '';
        $receiveEmail = $emailParams['receive_email'] ?? '';
        $emailPass = $emailParams['email_pass'] ?? '';
        $title = $templateData['title'] ?? '';
        $content = $templateData['content'] ?? '';
        $sendmail = $sendEmail; //发件人邮箱
        $sendmailpswd = $emailPass; //客户端授权密码,而不是邮箱的登录密码，就是手机发送短信之后弹出来的一长串的密码
        $send_name = $sendEmail;// 设置发件人信息，如邮件格式说明中的发件人，
        $toemail = $receiveEmail;//定义收件人的邮箱
        $to_name = '';//设置收件人信息，如邮件格式说明中的收件人
        $mail = new PHPMailer();
        $mail->isSMTP();// 使用SMTP服务
        $mail->CharSet = "utf8";// 编码格式为utf8，不设置编码的话，中文会出现乱码
        $mail->Host = env('MAIL_HOST');// 发送方的SMTP服务器地址
        $mail->SMTPAuth = true;// 是否使用身份验证
        $mail->Username = $sendmail;//// 发送方的
        $mail->Password = $sendmailpswd;//客户端授权密码,而不是邮箱的登录密码！
        $mail->SMTPSecure = env('MAIL_ENCRYPTION');// 使用ssl协议方式
        $mail->Port = env('MAIL_PORT');//  qq端口465或587）
        $mail->setFrom($sendmail, $send_name);// 设置发件人信息，如邮件格式说明中的发件人，
        $mail->addAddress($toemail, $to_name);// 设置收件人信息，如邮件格式说明中的收件人，
        $mail->addReplyTo($sendmail, $send_name);// 设置回复人信息，指的是收件人收到邮件后，如果要回复，回复邮件将发送到的邮箱地址
        $mail->Subject = $title;// 邮件标题
        $mail->isHTML(true);
        if (!empty($logId)) $mail->Body = $content;// 邮件正文
        //$mail->AltBody = "This is the plain text纯文本";// 这个是设置纯文本方式显示的正文内容，如果不支持Html方式，就会用到这个，基本无用
        if (!$mail->send()) { // 发送邮件
            return ['code' => 1, 'message' => $mail->ErrorInfo];
        } else {
            return ['code' => 0, 'message' => '发送成功'];
        }
    }

    /**
     * @Notes:获取随机发送邮件
     * @Interface getSendEmail
     * @author: wuyu
     * @Time: 2023/8/2   11:05
     */
    public function getSendEmail()
    {

        $emailList = [
            [
                'mail_host'=>'smtp.outlook.com',
                'mail_username'=>'customerservice1-@outlook.com',
                'mail_password'=>'xiaosi2023',
            ],
            [
                'mail_host'=>'smtp.outlook.com',
                'mail_username'=>'OrfeldCustomer@outlook.com',
                'mail_password'=>'1296110310.jr',
            ],
            [
                'mail_host'=>'smtp.outlook.com',
                'mail_username'=>'ORFELDwarrantyservice@outlook.com',
                'mail_password'=>'1296110310.jr',
            ],
        ];
        return $emailList;
    }

    public function emailoutlook($templateData,$emailParams,$logId=0)
    {

        $emailList = $this->getSendEmail();
         shuffle($emailList); //随机打乱顺序 比随机取数更能避免同时刻重复
        $emailInfo = $emailList[0] ?? [];

        $sendEmail = $emailParams['send_email'] ?? '';
        $returnReceiveEmail = $emailParams['return_receive_email'] ?? '';
        $receiveEmail = $emailParams['receive_email'] ?? '';
        $emailPass = $emailParams['email_pass'] ?? '';
        $title = $templateData['title'] ?? '';
        $content = $templateData['content'] ?? '';
        if (!empty($returnReceiveEmail)) $sendEmail = $returnReceiveEmail;

        $mail = new PHPMailer();
        $mail->isSMTP();
        $mail->Host = $emailInfo['mail_host'];
        $mail->SMTPAuth = true;
        $mail->Username =$emailInfo['mail_username'];
        $mail->Password = $emailInfo['mail_password'];
        $mail->SMTPSecure = env('MAIL_ENCRYPTION');
        $mail->Port = env('MAIL_PORT');
        $mail->setFrom($emailInfo['mail_username']);
        $mail->addAddress($receiveEmail);
        $mail->addReplyTo($sendEmail);// 设置回复人信息，指的是收件人收到邮件后，如果要回复，回复邮件将发送到的邮箱地址
        $mail->Subject = $title;
        $mail->isHTML(true);
        if (!empty($logId)) $mail->Body = $content;// 邮件正文
        if(!$mail->send()) {
            return ['code' => 1, 'message' => $mail->ErrorInfo];
        } else {
            return ['code' => 0, 'message' => '发送成功'];
        }

    }

}
